#***********************************************************
#* Copyright (c) 2006, Zhimin Zhan.
#* Distributed open-source, see full license in MIT-LICENSE
#***********************************************************

module RWebUnit

   # WebPage (children of AbstractWebPage) encapsulates a real web page.
   # For example,
   #  beginAt("/home")
   #  @browser.clickLinkWithText("/login")
   #  @browser.setFormElement("username", "sa")
   # Can be rewritten to
   #  beginAt("/home")
   #  home_page = HomePage.new
   #  login_page = home_page.clickLoginLink
   #  login_page.enterUserName("sa")
   #
   # So you only need change in LoingPage class if UI changes, which happen quite often.
   class AbstractWebPage

      # browser: passed to do assertion within the page
      # page_text: text used to identify the page, title will be the first candidate
      attr_accessor :browser, :page_text

      def initialize(ie, page_text=nil)
         @browser = ie
         @page_text = page_text
         assertOnPage
      end

      def assertTextPresent(text)
         @browser.assertTextPresent(text)
      end

      def assertTextInElement(elementID, text)
         @browser.assertTextInElement(elementID, text)
      end

      def assertOnPage()
         assertTextPresent(@page_text) if @page_text
      end

      def assertNotOnPage()
         assertTextNotPresent(@page_text) if @page_text
      end

      def submit
         @browser.submit
      end

      def getElementValue(elementId)
         @browser.getElemenValue(elementId)
      end

      def dumpResponse(stream = nil)
         @browser.dumpResponse(stream)
      end

     # Wait for specific seconds for an Ajax update finish.
      # Trick: In your Rails application,
      #     :loading 	=> "Element.show('search_indicator');
      #     :complete	=> "Element.hide('search_indicator');
      #
      #   <%= image_tag("indicator.gif", :id => 'search_indicator', :style => 'display:none') %>
      #
      # In your test case:
      #    wait_ajax_update("search_indicator", "30)
      #
      # Warning: this method has not been fully tested, if you are not using Rails, change your parameter accordingly.
      #
      def wait_ajax_update(element_id, seconds)
         count = 0
         while count < (seconds / 2) do
            search_indicator = @browser.getElementById(element_id)
            search_indicator_outer_html = search_indicator.outerHtml if search_indicator
            return true if search_indicator_outer_html && search_indicator_outer_html.include?('style="DISPLAY: none"')
            sleep 2;
            count = count + 1
         end
         return false
       end
       
   end

end
